function extend(des, src, override){
   if(src instanceof Array){
       for(var i = 0, len = src.length; i < len; i++)
            extend(des, src[i], override);
   }
   for( var i in src){
       if(override || !(i in des)){
           des[i] = src[i];
       }
   } 
   return des;
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function toformatTime(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
  
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function curDate(){
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return year+'年'+month+'月'+day+'日'
}

function headers(){
  return { "Content-Type": "application/x-www-form-urlencoded", "Cookie": "XDEBUG_SESSION=10632" };
}

function reqUrl(path,sign,data){
  var url = 'https://gongzheng.ma.cn/Lapp/' + path + '.html'
  //var url = 'https://s.huabanlu.com/index.php/Lapp/' + path + '.html'
  // var url = 'http://www.api.com/index.php/Lapp/' + path + '.html'
  if (typeof (sign) != "undefined"){
    url = url + '?identity_token=' + this.getUserdata('identity_token')
    for (var i in data){
      url += '&' + i + '=' + data[i]
    }
  }
  console.log('请求链接！' + url)
  return url
}

function getUserdata(key){
  return wx.getStorageSync(key) || {}
}
function getUserArr(key){
  return wx.getStorageSync(key) || []
}
function setUserdata(key,data){
  wx.setStorageSync(key , data)
}
function removeUserData(key) {
  wx.removeStorageSync(key) || []
}

function request(url,data,succ,fail,complete){
  let odata = {}
  if(getUserdata){
    odata = { 'identity_token': this.getUserdata('identity_token')};
  }
  console.log('identity_token==' + this.getUserdata('identity_token'))

  console.log('请求链接2！' + url)
  wx.request({
          url: reqUrl(url),
          header: headers(),
          method: 'post',
          data: extend(odata,data),
          success(res) {
            succ(res)
          },
          fail(res) {
            if(fail) fail(res);
            //尝试重启
            wx.reLaunch({
              url: 'pages/index/index'
            })
          },
          complete(res) {
            if(complete) complete(res);
          },
  })
}

function array_search(arr, val) {
  for (var i =0;i<arr.length;i++ ) {
    if (arr[i] == val) {
      return i;
    }
  }
  return -1;
}

function clear_all_input(){
    var brand_info = {}
    setUserdata('brand_info',brand_info)
    var transfer_info = []
    setUserdata('transfer_info',transfer_info)
    var receive_info = []
    setUserdata('receive_info',receive_info)
    var other = {}
    setUserdata('other',other)
}

function checkMail(val){
  if(val.length > 512) return false;
  var eReg = /\S*@\S*\.\S*/
  return eReg.test(val)
}

function checkDate(val){
  var eReg = /^\d{4}\-\d{2}\-\d{2}$/
  return eReg.test(val)
}

function checkPhone(val){
  var eReg = /^1[34578]\d{9}$/
  return eReg.test(val)
}

/*获取当前页url*/
function getCurrentPageUrl() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = currentPage.route //当前页面url
  return url
}

/*获取当前页带参数的url*/
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = currentPage.route //当前页面url
  var options = currentPage.options //如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

  return urlWithArgs
}

function showLoading(message) {
  if (wx.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.showLoading({
      title: message,
      mask: true
    });
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    wx.showToast({
      title: message,
      icon: 'loading',
      mask: true,
      duration: 20000
    });
  }
}

function hideLoading() {
  if (wx.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.hideLoading();
  } else {
    wx.hideToast();
  }
}

module.exports = {
  headers: headers,
  reqUrl: reqUrl,
  request: request,
  getUserdata: getUserdata,
  getUserArr: getUserArr,
  setUserdata: setUserdata,
  array_search: array_search,
  formatTime:formatTime,
  curDate:curDate,
  clear_all_input:clear_all_input,
  checkMail:checkMail,
  checkDate:checkDate,
  checkPhone:checkPhone,
  removeUserData:removeUserData,
  getCurrentPageUrl: getCurrentPageUrl,
  getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
  showLoading: showLoading,
  hideLoading: hideLoading,
  toformatTime: toformatTime
}
